package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import business.utilities.PassageTrainTheorique_Package;

import com.cedarsoftware.util.io.JsonWriter;

import externaldata.passageTrainTheorique.PassageTrainTheoriqueLive;


public class S_TrainSearch extends HttpServlet {
	private static final long serialVersionUID = 1L;


	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("json");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		@SuppressWarnings("unchecked")
		Map<String, List<PassageTrainTheoriqueLive>> trains = new HashMap<String, List<PassageTrainTheoriqueLive>>((Map<String, List<PassageTrainTheoriqueLive>>) request.getSession().getServletContext().getAttribute("paris_disponibles"));
		List<PassageTrainTheorique_Package> json = new ArrayList<PassageTrainTheorique_Package>();
		
		if(trains != null && !trains.isEmpty()) {
			String gare_dua = request.getParameter("gare_dua");
			if(gare_dua == null || gare_dua.equals("")) {
				for(List<PassageTrainTheoriqueLive> lptt : trains.values()) {
					for(PassageTrainTheoriqueLive ptt : lptt) {
						if(ptt.getPariAutorise()) {
							PassageTrainTheorique_Package pttp = new PassageTrainTheorique_Package();
							pttp.update(ptt);
							json.add(pttp);
						}
					}
				}
			}
			else {
				for(PassageTrainTheoriqueLive ptt : trains.get(gare_dua)) {
					if(ptt.getPariAutorise()) {
						PassageTrainTheorique_Package pttp = new PassageTrainTheorique_Package();
						pttp.update(ptt);
						json.add(pttp);
					}
				}
			}
			Collections.sort(json);
			//for(PassageTrainTheorique_Package pttp : json)
				//System.out.println(pttp.getPassageTrainTheorique().getArriveeTheorique());
			out.print(JsonWriter.objectToJson(json));
		}
		else {
			out.print("{}");
		}
		
		out.close();
	}
}